#include <arpa/inet.h> // inet_addr()
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h> // bzero()
#include <sys/socket.h>
#include <unistd.h> // read(), write(), close()
#include <errno.h>

#define MAX 512
#define SA struct sockaddr
void func(int sockfd)
{
    char buff[MAX];
    char bin[MAX];
    int count;
	int resp_len;
    int i = 0, j = 0;
    for (;;) {
        bzero(buff, sizeof(buff));
        printf("> ");
        count = 0;
        while ((buff[count++] = getchar()) != '\n')
            ;
		if (buff[0] == ':') {
			// user cmd
			if (strncmp(&buff[1], "read", 4) == 0) {
				sscanf(&buff[1+4+1], "%u", &resp_len);
				printf("Reading Response for %u bytes...\n", resp_len);
				bzero(buff, sizeof(buff));
				count = read(sockfd, buff, resp_len);
				for (i = 0; i < count; i ++) {
					printf("%02hhx ", buff[i]);
				}
				printf("\n");
			} else if ((strncmp(&buff[1], "exit", 4)) == 0) {
				printf("Client Exit...\n");
				break;
			}
		} else {
			// parse user req data
			for (i = 0; i < count; i ++) {
				if (buff[i] == ' ') {
					i++;
				} else {
					sscanf(&buff[i], "%02hhx", &bin[j]);
					i += 2;
					j++;
				}
			}
			// send user req data
			write(sockfd, bin, j);
			j = 0; // clear user req data
		}
    }
}

int main(int argc, char *argv[])
{
	int ret;
    int sockfd;
    struct sockaddr_in servaddr;

    // socket create and verification
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
        printf("socket creation failed...\n");
        exit(0);
    }
    else
        printf("Socket successfully created..\n");
    bzero(&servaddr, sizeof(servaddr));

    // assign IP, PORT
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr(argv[1]);
    servaddr.sin_port = htons(atoi(argv[2]));

    // connect the client socket to server socket
	ret = connect(sockfd, (SA*)&servaddr, sizeof(servaddr));
    if (ret) {
        printf("connection with the server failed with err %d...\n", errno);
        exit(ret);
    }
    else
        printf("connected to the server..\n");

    // function for chat
    func(sockfd);

    // close the socket
    close(sockfd);
}
